<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="状态">
                <a-select v-model="queryParam.status" placeholder="请选择">
                  <a-select-option v-for="it in statusList" :key="it.id" :value="it.id">{{
                    it.name
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="发送时间">
                <a-range-picker
                  show-time
                  v-model="queryParam.buildTime"
                  style="width: 100%"
                  :placeholder="['请选择开始日期', '请选择结束日期']"
                  valueFormat="YYYY-MM-DD HH:mm:ss"
                />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="用户">
                <!-- platformId -->
                <AWM-select v-model="queryParam.userId" placeholder="请选择用户" funStr="userListByNoAuth"></AWM-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="产品">
                <!-- platformId -->
                <AWM-select
                  v-model="queryParam.productId"
                  placeholder="请选择产品"
                  funStr="productByNoAuth"
                ></AWM-select>
              </a-form-item>
            </a-col>
            <!-- <a-col :md="(!advanced && 8) || 24" :sm="24"> -->
              <a-col :md="8" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => ((this.queryParam = {}), (this.need = {}))"
                  >重置</a-button
                >
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        showPagination="auto"
        :scroll="{ x: 'auto' }"
      >
        <span slot="receive" slot-scope="text">
          <ul>
            <li v-for="(it,i) in text.slice(0,2)" :key="it+''+i"><a-badge status="default" :text="it" /></li>
          </ul>
          <a @click="handleMore(text)" v-if="text.length > 2">查看更多</a>
        </span>
        <span slot="param" slot-scope="text">
          <div class="param-wrap">{{ text }}</div>
        </span>
        <span slot="ftype" slot-scope="text, record">
          {{ record.typeId1Name }}{{ record.typeId2Name ? ` - ${record.typeId2Name}` : '' }}
        </span>

        <span slot="status" slot-scope="text">
          <a-tag :color="text | statusFilter(statusList, 'status')">{{
            text | statusFilter(statusList, 'name')
          }}</a-tag>
        </span>
        <span slot ='amount' slot-scope='text'>￥{{text | NumberFormat}}</span>
        <span slot="details" slot-scope="text, record">
          <span class="default-wrap">总数: {{ record.receiveNum + record.curtailReceiveNum }}</span
          >&nbsp;&nbsp;
          <span class="success-wrap">成功: {{ record.successNum }}</span
          >&nbsp;&nbsp; <span class="default-wrap">未知: {{ record.unknownNum }}</span
          >&nbsp;&nbsp;
          <br/>
          <span class="danger-wrap">失败: {{ record.failureNum }}</span>&nbsp;&nbsp;
          <span class="danger-wrap">未提交: {{ record.unSubmitNumber }}</span>
        </span>
        <span slot="imageUrl" slot-scope="text">
          <template>
            <!-- <ul>
              <li v-for="it in text" :key="it.id">
                {{ it.fileUrl | filenameHidden }}</li>
            </ul> -->
            <AWM-file-list :list="text"></AWM-file-list>
          </template>
        </span>
        <span slot="remark" slot-scope="text">
          <template>
            <div class="remark-wrap">{{ text }}</div>
          </template>
        </span>
        <span slot="content" slot-scope="text" :title="text">
          <template>
            <div class="remark-wrap">{{ text }}</div>
          </template>
        </span>
        <span slot="action" slot-scope="text, record">
          <span>
            <!-- <a @click="handleLook(record)">查看回执</a>
            <a-divider type="vertical" /> -->
            <a @click="handleUnknow(record)">未提交号码</a>
          </span>
        </span>
      </s-table>
      <a-descriptions style="margin-top: 10px; width:300px;" :column="2" size="small">
        <a-descriptions-item label="总数"> {{ sum.success+sum.failure+sum.unknown | NumberFormat }} </a-descriptions-item>
        <a-descriptions-item label="成功数"> {{ sum.success | NumberFormat }} </a-descriptions-item>
        <a-descriptions-item label="发送金额"> ￥{{ sum.sendAmount | NumberFormat }} </a-descriptions-item>
        <a-descriptions-item label="失败数"> {{ sum.failure | NumberFormat }} </a-descriptions-item>
        <a-descriptions-item label="成本金额"> ￥{{ sum.platformAmount | NumberFormat }} </a-descriptions-item>
        <a-descriptions-item label="未知数"> {{ sum.unknown | NumberFormat }} </a-descriptions-item>
      </a-descriptions>
      <more-phone 
      :visible="more.visible" 
      :list="more.list"
      @ok="handleOk"
      @cancel="handleOk"
      ></more-phone>
      <unkonw-MSG-list :visible="unknow.visible" :data="unknow.list" @cancel="handleUnknowCancel"></unkonw-MSG-list>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { STable } from '@/components'
import AWMSelect from '@/components/AWMSelect'
import { financeLogAdd, financeLogUpdate } from '@/api/finance'
import { getSmsTimingList } from '@/api/sms'
import { msgStatusList } from '@/utils/other'
// import StepByStepModal from './modules/StepByStepModal'
import { mapGetters } from 'vuex'
import MorePhone from '@/components/MorePhone'
import {
  financeLogAddBatch
} from '@/api/login'
import UnkonwMSGList from './modules/UnkonwMSGList'

// id，发起用户，手机号码，标题，内容，图片附件，请求id，添加时间，定时发送，状态
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width:80,
  },
  {
    title: '发起用户',
    dataIndex: 'userName',
    width:'180px',
    customRender: (text, record) => `${text}(${record.userId})` || '--',
  },
  {
    title: '手机号码',
    dataIndex: 'receive',
    width: 180,
    scopedSlots: { customRender: 'receive' },
  },
  {
    title: '内容',
    width:'230px',
    dataIndex: 'content',
     scopedSlots: { customRender: 'content' },
  },
  {
    title: '发送详情',
    dataIndex: 'details',
    width:'230px',
    scopedSlots: { customRender: 'details' },
  },
  
  {
    title: '请求ID',
    dataIndex: 'requestId',
    width:'200px',
    customRender: (text) => text || '--',
    // scopedSlots: { customRender: 'remark' },
  },
  {
    title: '添加时间',
    dataIndex: 'addTime',
    width:'220px',
  },
  {
    title: '定时发送',
    dataIndex: 'timing',
    width: '200px',
    customRender: (text) => text || '--',
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: '200px',
    scopedSlots: { customRender: 'status' },
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 180,
    scopedSlots: { customRender: 'action' },
  },
]

export default {
  name: 'zz-timing-msg',
  components: {
    STable,
    MorePhone,
    AWMSelect,
    UnkonwMSGList
  },
  data() {
    this.columns = columns
    return {
      more: {
        visible: false,
        list: [],
      },
      open: false,
      check: {
        visible: false,
        confirmLoading: false,
        mdl: null,
      },
      typeIdList:[],
      need:{},
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      batch: {
        visible: false,
        confirmLoading: false,
      },
      // 查询参数
      parameter: {
        pageNum: 1,
        pageSize: 10,
      },
      sum: {
        unknown: 0,
        success: 0,
        failure: 0,
        sendAmount: 0,
        platformAmount: 0,
      },
      unknow:{
        visible: false,
        list: []
      },
      queryParam: {
      },
      data: [],
      // 状态
      statusList: msgStatusList,
      financeTypeList: [],
      // 排序
      sortJ: {
        addTime: 'add_time',
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        let sortJ = this.sortJ
        if (parameter.sortField) {
          parameter.sortJ = sortJ
        }
        // 附加属性
        let subParam = {}
        const requestParameters = Object.assign({}, parameter, this.queryParam)

        if (requestParameters.buildTime) {
          requestParameters.startTime = requestParameters.buildTime[0]
          requestParameters.endTime = requestParameters.buildTime[1]
          delete requestParameters.buildTime
        }
        // requestParameters.addUser = this.$store.getters.userInfo.id || 0
        return getSmsTimingList(requestParameters).then((res) => {
          if (parameter.pageNo == 1) {
            if(res.data.data.length){
              this.sum = {
                unknown: res.data.data[0].unknown || 0,
                success: res.data.data[0].success || 0,
                failure: res.data.data[0].failure || 0,
                sendAmount: res.data.data[0].sendAmount || 0,
                platformAmount: res.data.data[0].platformAmount || 0,
              }
            }else{
              this.sum = {
                unknown: 0,
                success: 0,
                failure: 0,
                sendAmount: 0,
                platformAmount: 0,
              }
            }
          }
          let result = {
            data: res.data.data.map((v) => {
              let paramReceive = JSON.parse(v.paramReceive) || ['']
              let overfrequency = []
              v.resExts ? (v.resExts = JSON.parse(v.resExts),overfrequency = v.resExts.overfrequency || []):null
              v.receive = paramReceive
              v.overfrequency = overfrequency.map(v=>{ return { phone: v}})
              return v
            }),
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize,
            totalCount: res.data.total,
            totalPage: res.data.pages,
          }
          return result
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
    }
  },
  created() {},
  computed: {
    ...mapGetters({'baseUrl':'baseUrl', 'userInfo': 'userInfo'}),
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
      }
    },
  },
  methods: {
    handleUnknow(record){
      this.unknow.visible = true
      this.unknow.list = record.overfrequency || []
    },
    handleUnknowCancel() {
      this.unknow.visible = false
      setTimeout(()=>{
        this.unknow.list = []
      }, 500)
    },
    handleChangeTypeId(value){
      let need = {};
      if(value.length == 1){
        need = this.financeTypeList.find(v=> v.id == value[0] )
      }else if(value.length == 2){
        need = this.financeTypeList.find(v=> v.id = value[0] )
        need = need.childTypeList.find(v=> v.id = value[1] )
      }else{
        need = {}
      }
      this.need = need;
    },
    
    handleCheckList(record) {
      this.check.mdl = { ...record }
      this.check.visible = true
    },
    handleCheckCancel() {
      this.check.visible = false
    },
    handleAdd() {
      this.mdl = null
      this.visible = true
    },
    
    handleEdit(record) {
      this.visible = true
      this.mdl = { ...record }
    },
    saveCB() {
      const form = this.$refs.createModal.form
      this.visible = false
      this.confirmLoading = false
      // 重置表单数据
      form.resetFields()
      // 刷新表格
      this.$refs.table.refresh()
    },
    handleOk(a_status) {
      const createModal = this.$refs.createModal
      const form = createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          values.useTime ? (values.useTime = values.useTime.format('YYYY-MM-DD HH:mm:ss')) : ''
          values.financeLogAttachList = createModal.getFile()
          if(values.typeId1.length == 2)
          values.typeId2 = values.typeId1[1]
          values.typeId1 = values.typeId1[0]
          // return false
          values.status = a_status
          if (values.id > 0) {
            financeLogUpdate(values)
              .then(() => {
                this.saveCB()
                this.$message.success('修改成功!')
              })
              .catch(() => {
                this.saveCB()
              })
          } else {
            delete values.id
            financeLogAdd(values)
              .then(() => {
                this.saveCB()
                this.$message.success(a_status == 0 ? '保存成功!':'提交成功!')
              })
              .catch(() => {
                this.saveCB()
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date()),
      }
    },
    handleDel(a_record) {
      let self = this
      const modal = self.$confirm({
        title: '财务类型删除',
        content: `是否删除财务类型:${a_record.name}`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => self.handleDelete(a_record.id, modal),
        onCancel: () => {},
      })
    },
    handleDelete(a_id, a_modal) {
      return new Promise((resolve, reject) => {
        let data = { id: a_id, status: -1 }
        financeLogUpdate(data)
          .then((res) => {
            this.$refs.table.refresh()
            this.$message.success('删除成功!')
            resolve()
          })
          .catch((err) => {
            a_modal.destroy()
            this.$message.error('操作失败!')
          })
      })
    },
    // piliang
    handleBatchAdd() {
      this.batch.visible = true
    },
    handleBatchAddOk() {
      let self = this
      let batchModal = self.$refs['batchModal']
      if (batchModal.financeLogList.length == 0) {
        self.$message.warning('数据为空')
        return false
      }
      self.batch.confirmLoading = true

      let data = {
        financeLogList: batchModal.financeLogList,
      }
      financeLogAddBatch(data)
        .then((res) => {
          self.batch.visible = false
          self.$message.success('批量添加成功!')
        })
        .finally(() => {
          self.batch.confirmLoading = false
        })
    },
    handleBatchAddCancel() {
      this.batch.visible = false
    },
    handleOk(){
      this.more.visible = false;
      this.more.list = [];
    },
    handleMore(a_data){
      console.log(111)
      this.more.visible = true
      this.more.list = a_data
    },
  },
}
</script>
<style scoped lang="less">
.param-wrap {
  min-width: 200px;
  max-width: 300px;
}

.a-tag-wrap {
  font-size: 12px;
  /deep/ .ant-tag {
    line-height: 18px;
    padding: 0 4px;
  }
  div {
    margin-bottom: 2px;
    &:last-child {
      margin-bottom: 0;
    }
  }
}
.success-wrap {
  color: #14d36a;
  font-size: 12px;
}
.default-wrap {
  color: #999;
  font-size: 12px;
}
.danger-wrap {
  color: #fc0119;
  font-size: 12px;
}
.remark-wrap {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
}
</style>

 